<template>
  <div>
    <el-form :inline="true">
      <el-form-item v-if="hasAuth('room:list')">{{showType==='table'?'列表模式':'全局模式'}}&nbsp;&nbsp;</el-form-item>
      <el-form-item v-if="hasAuth('room:list')">
        <el-tooltip :content="showType==='table'?'列表模式':'全局模式'"
                    placement="top">
          <el-switch
              @change="showModelChange"
              v-model="showType"
              active-color="#13ce66"
              inactive-color="#87CEEBFF"
              active-value="global"
              inactive-value="table">
          </el-switch>
        </el-tooltip>
      </el-form-item>
      <el-form-item v-if="hasAuth('room:list')">&nbsp;&nbsp;&nbsp;</el-form-item>
      <el-form-item v-if="hasAuth('room:list')">按信息搜索</el-form-item>
      <el-form-item v-if="hasAuth('room:list')">
        <el-input :placeholder="searchType"
                  v-model="search"
                  class="input-with-select"
                  @change="changeSearchInput"
                  :clearable=true>
          <el-select v-model="searchType" slot="prepend">
            <el-option label="房间编号" value="room_no"></el-option>
            <el-option label="房间名称" value="room_name"></el-option>
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="searchData"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item v-if="hasAuth('room:add')">
        <el-button type="primary" @click="editRoom(null)">新增房间</el-button>
      </el-form-item>
      <el-form-item v-if="hasAuth('room:update')">
        <el-popover
            placement="right"
            v-model="showBatchDownCard"
            width="180">
          <p style="color: red">确定批量下架这些房间吗？</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="showBatchDownCard = false;">取消</el-button>
            <el-button type="primary" size="mini"  @click="showBatchDownCard = false;batchHandle('down')">确定</el-button>
          </div>
          <el-button type="danger" slot="reference" v-show="!showBatchDownButton">批量下架</el-button>
        </el-popover>
      </el-form-item>
      <el-form-item v-if="hasAuth('room:delete')">
        <el-popover
            placement="right"
            v-model="showBatchDeleteCard"
            width="200">
          <p style="color: red">确定批量删除这些房间吗?</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="showBatchDeleteCard = false;">取消</el-button>
            <el-button type="primary" size="mini"  @click="showBatchDeleteCard = false;batchHandle('delete')">确定</el-button>
          </div>
          <el-button type="danger" slot="reference" v-show="!showBatchDeleteButton">批量删除</el-button>
        </el-popover>
      </el-form-item>
    </el-form>

    <div v-if="showType==='table'" style="width: 100%">
      <el-table
          v-if="hasAuth('room:list')" width="100%"
          :data="roomList" ref="roomList" border highlight-current-row
          @selection-change="selectionChange" >
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            fixed
            prop="roomNo"
            label="房间编号"
            width="80">
        </el-table-column>
        <el-table-column label="房间信息">
          <el-table-column
              prop="roomName"
              label="房间名称"
              width="120">
          </el-table-column>
          <el-table-column
              label="房间图片"
              width="200">
            <template slot-scope="scope">
              <el-image
                  style="width: 200px; height: 200px"
                  :src="scope.row.roomImages?scope.row.roomImages.split('|')[0]:''"
                  :preview-src-list="scope.row.roomImages?scope.row.roomImages.split('|'):[]"></el-image>
            </template>
          </el-table-column>
          <el-table-column
              prop="roomStatue"
              label="房间状态"
              width="100"
              :filters="[{ text: '下架', value: 0 },{ text: '待维修', value: 1 }, { text: '已锁定', value: 2 },
              { text: '已入住', value: 3 }, { text: '待打扫', value: 4 }, { text: '空闲', value: 5 }, ]"
              :filter-method="filterStatueTag"
              filter-placement="bottom-end">
            <template slot-scope="scope">
              <el-tag :type="roomStatue[scope.row.roomStatue].type">{{roomStatue[scope.row.roomStatue].statue}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
              prop="roomFloor"
              label="楼层"
              width="60">
          </el-table-column>
          <el-table-column
              prop="roomComment"
              label="房间主题"
              width="200"
              show-overflow-tooltip>
          </el-table-column>
          <el-table-column
              prop="roomDesc"
              label="房间描述"
              show-overflow-tooltip>
          </el-table-column>
        </el-table-column>
        <el-table-column
            v-if="hasAuth('room:update')"
            fixed="right" label="操作" width="60">
          <template slot-scope="scope">
            <el-button @click="editRoom(scope.row)"  type="text" size="small">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
            @size-change="userPageSizeChange"
            @current-change="userPageCurrentChange"
            :current-page="current"
            :page-sizes="[3, 6, 10, 20, 999]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </div>
    <div v-else style="width: 100%">
      <div v-for="(item,index) in roomList" v-if="hasAuth('room:list')"
           :style="{backgroundColor:roomStatue[item.roomStatue].bgc}"
           class="show-room-nav">
        <div @click="editRoom(item)" style="cursor:pointer" v-if="hasAuth('room:update')">
          <div class="show-room-text">{{item.roomName}}</div>
          <div class="show-room-text">状态：{{roomStatue[item.roomStatue].statue}}</div>
          <div class="show-room-text">房间编号：{{item.roomNo}}</div>
        </div>
        <el-tooltip placement="bottom" effect="light" :disabled="item.roomStatue !== 3"
                    :open-delay="600">
          <div slot="content" style="font-size: 18px">
            姓名:{{userInfo.orderName}}<br/>电话:{{userInfo.orderPhone}}<br/>邮箱:{{userInfo.orderEmail}}</div>
          <el-image :src="item.roomImages!==null?item.roomImages.split('|')[0]:''"
                    :style="item.roomStatue === 2?'cursor:pointer':''"
                    @mouseover="showUserInfo(item)" class="room-image-item">
            <div slot="error" class="image-slot">
              <div>暂无图片</div>
            </div>
          </el-image>
        </el-tooltip>
      </div>
    </div>

    <!--编辑 新增 房间-->
    <el-dialog
        title="房间操作" :visible="editRoomShow"
        :modal-append-to-body="false" :close-on-click-modal="false"
        width="60%" center :before-close="editRoomClose">
      <el-form ref="roomForm" :rules="roomRules" :model="room" label-width="auto">
        <el-row>
          <el-col :span="8">
            <el-form-item label="房间编号">
              <el-input :value="EditOrAddFlag?'房间编号自动生成':room.roomNo"  disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="房间状态" prop="roomState">
              <el-select v-model="room.roomStatue" style="width: 100%">
                <el-option
                    :disabled="EditOrAddFlag"
                    v-for="(item,index) in roomStatue"
                    :key="index"
                    :label="item.statue"
                    :value="index">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="房间类型">
              <el-button style="width: 100%" :disabled="EditOrAddFlag" @click="getRoomTypeDetail(room.roomTypeId)">查看房间类型</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="房间类型" v-if="EditOrAddFlag">
          <el-cascader
              v-model="selected" clearable :options="selector" style="width: 100%"
              :props="{ expandTrigger: 'hover' }"></el-cascader>
        </el-form-item>
        <el-form-item label="房间名称" prop="roomName">
          <el-input v-model="room.roomName"></el-input>
        </el-form-item>
        <el-form-item label="房间描述" prop="roomDesc">
          <el-input v-model="room.roomDesc"></el-input>
        </el-form-item>
        <el-form-item label="房间主题" prop="roomComment">
          <el-input v-model="room.roomComment"></el-input>
        </el-form-item>
        <el-form-item label="房间图片">
          <el-upload
              ref="uploadRoomImage"
              :append-to-body="true" action="#" list-type="picture-card" multiple :limit="8" :on-exceed="limitUploadImage"
              :on-change="uploadImageChange" :file-list="roomImageList"
              :auto-upload="false">
            <div slot="tip" class="el-upload__tip">{{EditOrAddFlag?'上传':'修改'}}图片 (只能上传JPG/GIF/PNG/BMP 文件，且不超过10MB)</div>
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="uploadImageRemovePreview(file)">
              <i class="el-icon-zoom-in"></i>
            </span>
            <span class="el-upload-list__item-delete" @click="uploadImageRemove(file)">
              <i class="el-icon-delete"></i>
            </span>
          </span>
            </div>
          </el-upload>
          <el-dialog :append-to-body="true" :visible.sync="showUploadImage">
            <img width="100%" :src="showUploadImageUrl" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoomClose">取 消</el-button>
        <el-button type="primary" @click="okEditRoom">确 定</el-button>
      </span>
    </el-dialog>

    <!--显示房间类型数据-->
    <el-drawer
        title="房间类型"
        :visible="showRoomType"
        @close="showRoomType = false"
        direction="rtl">
      <el-card>
        <el-image
            style="width: 200px; height: 200px"
            :src="roomType.roomImages?roomType.roomImages.split('|')[0]:''"
            :preview-src-list="roomType.roomImages?roomType.roomImages.split('|'):[]"></el-image>
        <div>房间类型：{{roomType.roomType}}</div>
        <div>房间床型：{{roomType.roomBed}}</div>
        <div>房间描述：{{roomType.roomDesc}}</div>
        <div>所在楼层：{{roomType.roomFloor}}楼</div>
        <div>房间数量：{{roomType.roomNum}}间</div>
        <div>房间价格：{{roomType.roomPrice}}元</div>
        <div>房间大小：{{roomType.roomSize}}平方米</div>
      </el-card>
    </el-drawer>

    <admin-footer/>
  </div>
</template>

<script>
import {
  addRoom,
  batchHandleRoom,
  getAllRoom,
  getRoomTypeByRoomId,
  getSelectDataForRoomType,
  updateRoom
} from "@/network/room";
import {getUserSimpleByRoomNo} from "@/network/order";
import {generatorArray} from "@/utils/util";
import AdminFooter from "@/components/conment/adminfooter/AdminFooter";
import {hasPermission} from "@/utils/mixin";
export default {
  name: "Order",
  components: {AdminFooter},
  mixins:[hasPermission],
  data() {
    return {
      roomList:[],
      room:{},
      tempRoom:{},
      roomStatue: [
        {'statue':'下架','type':'info','bgc':'#5b6666'},
        {'statue':'待维修','type':'danger','bgc':'#ee1313'},
        {'statue':'已锁定','type':'primary','bgc':'#8811ea'},
        {'statue':'已入住','type':'primary','bgc':'#16a0ef'},
        {'statue':'待打扫','type':'warning','bgc':'#e36623'},
        {'statue':'空闲','type':'success','bgc':'#67cd73'},
      ],//订单状态
      roomRules:{
        roomStatue:[
          {required: true, message: '请选择状态', trigger: 'blur' },
        ],
        roomName:[
          { required: true, message: '请输入房间名称', trigger: 'blur' },
        ],
        roomDesc:[
          { required: true, message: '请输入描述', trigger: 'blur' },
        ],
        roomComment:[
          { required: true, message: '请输入主题', trigger: 'blur' },
        ],
      },
      roomType:{},

      selector:[],
      selected:[],
      showRoomType:false,

      searchType:'room_no',
      search:'',

      selectedRows:[],//选中的行
      editRoomShow:false,
      EditOrAddFlag:false,
      showBatchDownCard:false,//批量下架
      showBatchDownButton:true,//批量下架按钮
      showBatchDeleteCard:false,
      showBatchDeleteButton:true,
      userInfo:{},

      showType:'列表模式',

      current:1,
      size:3,
      total:0,

      showUploadImageUrl: '',//上传图片显示
      showUploadImage: false,
      roomImageList:[],
    }
  },
  methods:{
    //移除上传的图片
    uploadImageRemove(file) {
      let s = this.$refs.uploadRoomImage.$data.uploadFiles
      s.splice(s.findIndex(s=>s.name === file.name),1)
    },
    //显示上传的图片
    uploadImageRemovePreview(file) {
      this.showUploadImageUrl = file.url;
      this.showUploadImage = true;
    },
    //限制上传数量
    limitUploadImage(){
      this.$message.error('最多上传8张图片 0.0')
    },
    //文件类型检测
    checkFileOk(file) {
      const isJPG = file.type === 'image/jpeg';
      const isGIF = file.type === 'image/gif';
      const isPNG = file.type === 'image/png';
      const isBMP = file.type === 'image/bmp';
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!');
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!');
        return false
      }
      return (isJPG || isBMP || isGIF || isPNG) && isLt10M;
    },
    //文件状态改变
    uploadImageChange(file, fileList){
      if (this.checkFileOk(file.raw)) {//文件类型检查通过
        let s = fileList.filter(s=>s.name===file.raw.name)
        if (s.length>1){
          this.$message.error(file.name+" 文件已存在！")
          fileList.pop()
        }
      }else {
        fileList.pop()
      }
    },
    //修改房间信息
    editRoom(row){
      if (row){//编辑
        if (row.roomImages){//编辑的房间有图片
          //图片显示
          this.roomImageList = row.roomImages.split('|').map(res => {
            return {name: res.substring(res.lastIndexOf('/') + 1, res.length), url: res}
          })
        }
        this.room = JSON.parse(JSON.stringify(row))
        this.tempRoom = JSON.parse(JSON.stringify(row))
        this.EditOrAddFlag = false

      }else {//添加
        this.room = {}
        this.tempRoom = {}
        this.roomImageList = []
        this.$set(this.room,'roomStatue',5)
        this.EditOrAddFlag = true
      }
      this.editRoomShow = true
    },
    //关闭修改增加
    editRoomClose(){
      this.editRoomShow = false
      this.$refs.roomForm.clearValidate()
      this.$refs.uploadRoomImage.clearFiles()
      this.showUploadImageUrl = ''
      this.roomImageList = []
      this.room = {}
      this.tempRoom = {}
      this.selected = []
    },
    //修改房间数据
    okEditRoom: async function (){
      await this.$refs.roomForm.validate(async (valid) => {
        if (valid) {
          if (this.EditOrAddFlag) {//添加房间数据
            if (this.$refs.uploadRoomImage.uploadFiles.length===0){
              this.$message.error('请上传房间图片')
              return
            }else if (this.selected.length===0){
              this.$message.error('请选择房间类型')
              return
            }
            let form = new FormData()
            this.$refs.uploadRoomImage.uploadFiles.forEach(f => {
              form.append('roomImage', f.raw)//图片数据
            })
            for(let i in this.room)//将属性遍历到FormData中
              form.append(i,this.room[i])
            form.append("room",JSON.stringify(this.room))
            form.append("roomType",this.selected)
            await addRoom(form).then(async res=>{
              this.getOrSearchRoom(this.current, this.size, '', '')
              this.$message.success('添加成功')
            })
          } else {//修改房间信息
            let form = new FormData()
            let temp = []
            this.$refs.uploadRoomImage.uploadFiles.forEach(res=>{
              if (this.room.roomImages.indexOf(res.url)===-1){//不存在
                form.append('roomImage', res.raw)
              }else {
                temp.push(res.url)
              }
            })
            this.room.roomImages = temp.join('|')
            if (JSON.stringify(this.room) !== JSON.stringify(this.tempRoom) || form.has('roomImage')) {
              for(let i in this.room)//将属性遍历到FormData中
                form.append(i,this.room[i])
              await updateRoom(form).then( async res => {
                this.getOrSearchRoom(this.current, this.size, '', '')
                this.$message.success('修改成功')
              })
            }
          }
          this.editRoomClose()
        } else {
          console.log('表单验证失败')
        }
      });
    },
    //勾选  多选操作
    selectionChange(val){
      let enables = val.filter(res=>{
        return res.roomStatue === 0//状态为下架
      })
      let lock = val.filter(res=>{
        return res.roomStatue === 2//状态锁定
      })
      let disables = val.filter(res=>{
        return res.roomStatue !== 0 && res.roomStatue !== 2//状态不为下架 和锁定
      })//
      if (Object.keys(enables).length === 0 && Object.keys(disables).length === 0 ){
        this.showBatchDeleteButton = true
        this.showBatchDownButton = true
      }else if (Object.keys(enables).length === 0 && Object.keys(disables).length !== 0 && Object.keys(lock).length === 0){
        this.showBatchDeleteButton = false
        this.showBatchDownButton = false
      }else if (Object.keys(enables).length !== 0 && Object.keys(disables).length === 0 && Object.keys(lock).length === 0){
        this.showBatchDownButton = true
        this.showBatchDeleteButton = false
      }
      this.selectedRows = val
    },
    //批量操作
    batchHandle(type){
      batchHandleRoom(type,this.selectedRows.map(res=>res.id)).then(res=>{
        //刷新数据
        this.getOrSearchRoom(this.current,this.size,null,null)
        this.$message.success('操作成功')
      })
      this.afterBatchFilter()
    },
    //搜索框数据改变
    changeSearchInput(){
      if (this.search===''){
        this.getOrSearchRoom(this.current,this.size,'','')
      }
    },
    //数据搜索
    searchData(){
      if (this.search!==''){//数据不为空
        this.getOrSearchRoom(this.current,this.size,this.searchType,this.search)
      }else {
        this.$message.warning("请输入数据后再查询")
      }
    },
    //房间状态过滤
    filterStatueTag(value, row){
      //清除选中状态
      this.$refs.roomList.clearSelection()
      return row.roomStatue === value
    },
    //每页数据条数改变
    userPageSizeChange(val){
      this.size = val
      this.getOrSearchRoom(this.current,this.size,'','')
    },
    //页数改变
    userPageCurrentChange(val){
      this.current = val
      this.getOrSearchRoom(this.current,this.size,'','')
    },
    //显示房间类型数据
    getRoomTypeDetail(roomTypeId){
      if (roomTypeId){
        //获取房间类型数据
        getRoomTypeByRoomId(roomTypeId).then(res=>{
          this.roomType = res.data.data
        })
        this.showRoomType = true
      }else {
        this.$message.error('房间类型未匹配到')
      }
    },
    showUserInfo(room){
      if (room.roomStatue===3){
        setTimeout(()=>{
          getUserSimpleByRoomNo(room.roomNo).then(res=>{
            this.userInfo = res.data.data
          })
        },500)//悬停500ms
      }
    },
    //显示模式切换
    showModelChange(){
      if (this.showType === 'global'){
        this.afterBatchFilter()
        this.getOrSearchRoom(-1,-1,'','')
      }else {
        this.current = 1
        this.size = 3
        this.getOrSearchRoom(this.current,this.size,'','')
      }
    },
    //过滤批量操作之后
    afterBatchFilter(){
      this.$refs.roomList.clearFilter()//清除筛选
      this.$refs.roomList.clearSelection()//清除选中状态
    },
    getOrSearchRoom(current,size,type,data){
      getAllRoom(current,size,type,data).then(res=>{
        if (res.data.data.records.length === 0)
          this.$message.warning("未找到符合条件的数据")
        else{
          this.roomList = res.data.data.records
          this.size = res.data.data.size
          this.current = res.data.data.current
          this.total = res.data.data.total
        }
      })
    },
  },
  created() {
    //获取所有房间信息
    this.getOrSearchRoom(this.current,this.size,'','')
    //新增房间，获取所有房间类型
    getSelectDataForRoomType().then(res=>{
      let s = res.data.data
      s.forEach((item,index)=>{
        let father = {
          label:item.roomType,
          value:item.roomTypeNo,
          children:[]
        }
        let roomFloor = item.roomFloor.split('-')
        let roomBed = item.roomBed.split('|')
        let roomPrice = item.roomPrice.split('|')
        let roomSize = item.roomSize.split('|')
        roomBed.forEach((item,index)=>{
          let children = {
            label:item+'-'+roomPrice[index]+'元-'+roomSize[index]+'平方米',
            value:item,
            children:[]
          }
          generatorArray(roomFloor[0],roomFloor[1],1).forEach((item)=>{
            children.children.push({
              label:item+'楼',
              value:item,
            })
          })
          father.children.push(children)
        })
        this.selector.push(father)
      })
    })
  }
}
</script>
<style scoped>
  .show-room-nav {
    display: inline-block;
    width: 200px;
    height: 200px;
    margin: 10px;
  }
  .show-room-text {
    text-align: center;
  }
  .room-image-item {
    width: 200px;
    height: 150px;
    background-color: #6f6a6a;
  }
  .image-slot div{
    margin: 0 auto;
    font-size: 30px;
    text-align: center;
  }
</style>